package com.xudow.app.newui.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;

/**
 * Created by Administrator on 2016/8/14.
 */
public class MyGridView extends GridView {
    int columns;
    public MyGridView(Context context) {
        super(context);
    }

    public MyGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyGridView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    }
    public void setMyNumColumns(int n){
        columns=n;
        setNumColumns(n);
    }
    public int getColumns(){
        return columns;
    }
    @Override
    public void setAdapter(ListAdapter adapter) {
        super.setAdapter(adapter);
        int height;
        View itemview=adapter.getView(0,null,null);
        itemview.measure(0,0);
        int itemHeight=itemview.getMeasuredHeight();

        if (0==adapter.getCount()%columns){
            height=(adapter.getCount()/columns)*itemHeight;
        }else {
            height=(adapter.getCount()/columns + 1) * itemHeight;
        }
        LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,height);
        setLayoutParams(layoutParams);
        invalidate();
    }
}
